<script setup lang="ts">
import {computed, ref} from 'vue'
import type ImageProp from "@/components/image/ImageProp.ts";

const props = withDefaults(defineProps<ImageProp>(), {
  width: "100%",
  height: "100%",
  preview: false,
  objectFit: "contain",
  objectPosition: "center center"
})

//img标签的样式
const styleStr = computed(() =>
    `
     width:${props.width};
     height:${props.height};
     object-fit:${props.objectFit};
     object-position:${props.objectPosition};
    `
)

const showPreview = ref(false)

const openPreview = () => {
  if (props.preview && props.src != "#") {
    showPreview.value = true
  }
}

const closePreview = () => {
  if (props.preview) {
    showPreview.value = false
  }
}

// 处理滚轮缩放
const scale = ref(1)
const handleWheel = (e: WheelEvent) => {
  e.preventDefault()
  const delta = e.deltaY > 0 ? -0.1 : 0.1
  scale.value = Math.min(5, Math.max(0.5, scale.value + delta))
}
</script>

<template>

  <div class="preview-container" @click.stop>
    <img v-bind="$attrs" :src="src" :alt="alt" :style="styleStr" @dblclick="openPreview" class="main-image"/>
  </div>

  <teleport to="body">
    <!-- 原生预览弹窗 -->
    <div v-if="showPreview" class="preview-modal" @click.self="closePreview" @wheel="handleWheel">
      <img :src="src" class="preview-image" :alt="alt" :style="{ transform: `scale(${scale})` }"/>
    </div>
  </teleport>
</template>

<style scoped>
.preview-container {
  width: 100%;
  height: 100%;
  position: relative;
  display: inline-block;
  cursor: pointer;
}

.main-image {
  display: block;
  object-fit: contain;
}

.main-image:hover {
  transform: scale(1.1);
}

.preview-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.7);
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
}


</style>
